//
//  BdjlxqVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/11.
//

import UIKit

protocol BdjlxqVCDelegate: class {
    func deleteBdjlxq(_ data: [String: Any])
}

class BdjlxqVC: BaseVC {
    
    weak var delegate: BdjlxqVCDelegate?
    
    var data: [String: Any]!
    var wavPath: String!
    
    var scrollView: UIScrollView!
    
    var line_view: EWELineScrollView!
    var sp_view: UIView!
    
    var name: UILabel!
    var sg: UILabel!
    var tz: UILabel!
    var tw: UILabel!
    var phcd: UILabel!
    var sfzj: UILabel!
    var sfss: UILabel!
    var cjcs: UILabel!
    var cjdz: UILabel!
    
    // pcm 波形图数据源
    var pcmBArray: [String] = []

    // 播放
    var play_button: UIButton!
    // 时间
    var play_time: UILabel!
    // 进度
    var play_line: UISlider!
    
    var player: LGFAudioPlayer!
    
    var isPlay: Bool = false
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player.paused()
    }
    
    deinit {
        debugPrint("LGFAudioPlayer 已释放")
        player?.stop()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        initData()
        player = LGFAudioPlayer()
        player.delegate = self
        line_view.scroll_back.delegate = self
        setLineData()
    }
    
    func initData() {
        name.text = (data["name"] as? String) ?? ""
        sg.text = "身高(cm)：" + ((data["height"] as? String) ?? "")
        tz.text = "体重(kg)：" + ((data["weight"] as? String) ?? "")
        tw.text = "体位：" + ((data["position_s"] as? String) ?? "")
        phcd.text = "配合程度：" + ((data["coordinate_s"] as? String) ?? "")
        sfzj.text = "是否镇静：" + (((data["calm"] as? String) ?? "") == "0" ? "否" : "是")
        sfss.text = "是否手术：" + (((data["operation"] as? String) ?? "") == "0" ? "否" : "是")
        cjcs.text = "采集场所：" + ((data["site_s"] as? String) ?? "")
        cjdz.text = "采集地址：" + ((data["collectionAddress"] as? String) ?? "")
        wavPath = LGF_Documents_WAV + ((data["wav_path"] as? String) ?? "")
    }
    
    @objc func s_delete() {
        let alertVC = UIAlertController.init(title: nil, message: "确定删除该样本吗?", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { [weak self] (action) in
            self?.navigationController?.popViewController(animated: true)
            var rdataArray: [Any] = (UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? [])
            for (i, data1) in rdataArray.enumerated() {
                if let data2 = data1 as? [String: Any] {
                    if let name = data2["name"] as? String {
                        if let name2 = self?.data["name"] as? String {
                            if let pcm_path = self?.data["pcm_path"] as? String {
                                if let wav_path = self?.data["wav_path"] as? String {
                                    if name2 == name {
                                        self?.removePcm(LGF_Documents_PCM + pcm_path)
                                        self?.removePcm(LGF_Documents_WAV + wav_path)
                                        rdataArray.remove(at: i)
                                        UserDefaults.standard.setValue(rdataArray, forKey: LGF_BD_WAV_ARRAY)
                                        self?.delegate?.deleteBdjlxq(self!.data)
                                        return
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }))
        alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
        UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
    }
    
    @objc func s_upload() {
        SVProgressHUD.showError("功能开发中")
    }
    
}

extension BdjlxqVC: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !scrollView.isTracking && !scrollView.isDragging && !scrollView.isDecelerating {
            return
        }
        let value = CGFloat(self.play_line.maximumValue) * (scrollView.contentOffset.x) / (scrollView.contentSize.width - scrollView.lgf_Width)
        player.seek(Float(value))
        play_time.text = player.getAllTime(Int(value) * 1000) + "/" + player.getAllTime(Int(self.play_line.maximumValue) * 1000)
        play_line.setValue(Float(value), animated: false)
        paused()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !scrollView.isDragging {
            if isPlay {
                resume()
            }
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if isPlay {
            resume()
        }
    }
    
    func run(_ value: Float) {
        self.play_line!.value = value
        self.scroll(value)
        self.play_time.text = player.getTime() + "/" + self.player.getAllTime(Int(self.play_line.maximumValue) * 1000)
    }
    
    func setLineData() {
        if self.pcmBArray.count == 0 {
            let pcm = LGF_Documents_PCM + ((data["pcm_path"] as? String) ?? "")
            do {
                let fileData = try Data.init(contentsOf: URL.init(fileURLWithPath: pcm))
                let fileDataStr = fileData.hexString()
                self.pcmBArray = self.getStrCountArray(fileDataStr, 4)
            } catch {
                debugPrint(error)
            }
            self.reloadLine({ (i, sp) in
                let l = (i * self.pcmBArray.count / 100)
                let r = ((i + 1) * self.pcmBArray.count / 100)
                let nums = Array(self.pcmBArray[l..<r])
                var numss: [Double] = []
                for (i, v) in nums.enumerated() {
                    if i % 40 == 0 {// 取余 40
                        let num = EWEFilter.getComplement(v)
                        numss.append(num)
                    }
                }
                sp.show(numss, 1)
            })
        }
    }
    
    func reloadLine(_ call: @escaping ((Int, LineBackView2) -> Void)) {
        var i = 0
        Timer.lgf_RunTimer(self, S: 0.025) { [weak self] (timer) in
            if let v = self?.sp_view.subviews[i] as? LineBackView2 {
                call(i, v)
            }
            i += 1
            if i == (self?.sp_view.subviews.count)! {
                timer?.lgf_StopTimer()
                return
            }
        }
    }
    
    func scroll(_ value: Float) {
        if self.pcmBArray.count == 0 || self.play_line.maximumValue == 0 {
            self.line_view.scroll_back.setContentOffset(CGPoint.zero, animated: false)
            return
        }
        self.line_view.scroll_back.setContentOffset(CGPoint.init(x: CGFloat(value) / CGFloat(self.play_line.maximumValue) * (self.line_view.scroll_back.contentSize.width - self.line_view.scroll_back.lgf_Width), y: 0), animated: false)
    }
    
    func paused() {
        player.paused()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "bofang"), for: .normal)
    }
    
    func stop() {
        isPlay = false
        play_line.setValue(0, animated: false)
        line_view.scroll_back.setContentOffset(CGPoint.zero, animated: false)
        player?.stop()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "bofang"), for: .normal)
    }
    
    func resume() {
        isPlay = true
        player.resume()
        play_button.setBackgroundImage(#imageLiteral(resourceName: "zanting"), for: .normal)
    }
    
    func play(_ path: String) {
        isPlay = true
        player.playFile(wavPath)
        play_button.setBackgroundImage(#imageLiteral(resourceName: "zanting"), for: .normal)
    }
    
    @objc func playNow(_ sender: UIButton) {
        if wavPath.count == 0 {
            return
        }
        if player.state == .playing {
            isPlay = false
            paused()
        } else if player.state == .paused {
            resume()
        } else {
            play(wavPath)
        }
    }
    @objc func s_end(_ sender: UISlider) {
        if isPlay {
            resume()
        }
    }
    @objc func s_changed(_ sender: UISlider) {
        player.seek(sender.value)
        play_time.text = player.getAllTime(Int(sender.value) * 1000) + "/" + player.getAllTime(Int(self.play_line.maximumValue) * 1000)
        scroll(sender.value)
        paused()
    }
    @objc func s_tap(_ sender: UITapGestureRecognizer) {
        let touchPoint = sender.location(in: play_line)
        let value = Float(play_line.maximumValue - play_line.minimumValue) * Float(touchPoint.x / play_line.lgf_Width)
        scroll(value)
        play_line.setValue(value, animated: true)
        player.seek(value)
    }
}

extension BdjlxqVC: LGFAudioPlayerDelegate {
    func LGFAudioPlayerState(_ player: STKAudioPlayer) {
        self.play_line.maximumValue = Float(player.duration)
        self.play_time.text = "00:00" + "/" + self.player.getAllTime(Int(self.play_line.maximumValue) * 1000)
    }
    
    func LGFAudioPlayerRun(_ player: STKAudioPlayer) {
        self.run(Float(player.progress))
    }
    
    func LGFAudioPlayerStop(_ player: STKAudioPlayer) {
        self.stop()
    }
}
